<template>
    <div style="padding: 20px;margin-top:20px;margin-bottom: 20px;" v-loading="loading">
        <el-form ref="formRef" :model="dataForm" label-width="120px" :inline="true" :rules="rules">
            <page-main title="基础信息">
                <el-form-item label="模板名称" prop="templateName">
                    <el-input v-model="dataForm.templateName" placeholder="请输入" :disabled="pageType == 'look'" />
                </el-form-item>
                <el-form-item label="控制方式" prop="controlBy">
                    <el-select v-model="dataForm.controlBy" :disabled="pageType == 'look'" style="width:214px">
                        <el-option v-for="item in CTROL_METHODS" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择年份" prop="years" v-if="dataForm.controlBy == 'CYCLE'">
                    <el-select v-model="dataForm.years" clearable filterable :disabled="pageType == 'look'"
                        style="width:214px">
                        <el-option v-for="item in yearOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="自定义时间" prop="date" v-if="dataForm.controlBy == 'CUSTOM_TIME_RANGE'">
                    <el-date-picker v-model="dataForm.date" type="monthrange" range-separator="至" start-placeholder="开始"
                        end-placeholder="结束" :disabled="pageType == 'look'" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="循环周期" prop="cycleType">
                    <el-select v-model="dataForm.cycleType" filterable :disabled="pageType == 'look'"
                        style="width:214px">
                        <el-option v-for="item in weeksList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="启用状态" prop="enabled">
                    <el-select v-model="dataForm.enabled" style="width:192px" :disabled="pageType == 'look'">
                        <el-option v-for="item in STATUS_LIST" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="模板分类" prop="templateType">
                    <el-select v-model="dataForm.templateType" style="width:214px" :disabled="pageType == 'look'">
                        <el-option v-for="item in TEMPLATE_CLASSIFY" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </page-main>
            <page-main title="预算科目维度" style="margin-top:15px">
                <template #title>
                    <!-- <el-button type="primary" v-if="pageType != 'look'" @click="importHandle" :loading="importLoading">
                        导入
                    </el-button> -->

                </template>
                <div class="search-box">
                    <el-form :model="formInline" @onReset="searchReset" ref="formInlineRef">
                        <el-form-item label="预算科目" prop="subject">
                            <el-select v-model="formInline.subject" filterable multiple collapse-tags clearable
                                style="width:350px">
                                <el-option v-for="item in useSubjectList" :key="item.id"
                                    :label="item.label + item.categoryCode" :value="item.id">
                                    <span style="float: left">{{ item.label }}</span>
                                    <span style="float: right; font-size: 13px;">{{ item.categoryCode }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="费用类型" prop="feeType">
                            <el-select v-model="formInline.feeType" filterable multiple collapse-tags clearable
                                style="width:350px">

                                <el-option v-for="item in feeTypeOptions" :key="item.id"
                                    :label="item.typeName + item.typeCode" :value="item.id">
                                    <span style="float: left">{{ item.typeName }}</span>
                                    <span style="float: right; font-size: 13px;">{{ item.typeCode }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button type="primary" @click="searchClick()">查询</el-button>
                            <el-button @click="searchReset()">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <div class="subject-con">
                    <el-row :gutter="40">
                        <el-col :span="12">
                            <div>
                                <SubjectTree :dataSource="dataSource" :interFaceInfo="interFaceInfo"
                                    @on-nodeClick="nodeClick" :pageType="pageType" @on-update="updateSubject"
                                    @on-deleteSubject="deleteSubject">
                                </SubjectTree>
                            </div>
                            <div v-if="isSearch && treeLen.length == 1" class="search-text">未搜索到结果</div>
                            <div v-if="!isSearch && treeLen.length == 1" class="search-text">~快去添加数据吧~</div>
                        </el-col>
                        <el-col :span="12">
                            <div>
                                <el-form-item label="关联费用类型" prop="type" style="width:100%" label-width="160px">

                                    <el-button link @click="opendFeeTypeDialog()">{{ Array.isArray(dataForm.type) &&
                                        dataForm.type.length > 0 ? `已关联 ${Array.isArray(dataForm.type) &&
                                        dataForm.type.length}
                                        个`: '选择费用类型' }}</el-button>
                                </el-form-item>
                            </div>
                            <div>
                                <el-form-item label="预算控制" prop="limitExceed" style="width:100%" label-width="160px">
                                    <el-select v-model="dataForm.limitExceed" style="width:100%"
                                        :disabled="pageType == 'look'" @change="selectContrl(dataForm.limitExceed)">
                                        <el-option v-for="(item, index) in controlOptions" :key="index"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </div>
                            <div>
                                <el-form-item label="超额控制" prop="afterExceed" style="width:100%" label-width="160px">
                                    <el-select v-model="dataForm.afterExceed" style="width:100%"
                                        :disabled="pageType == 'look'"
                                        @change="selectAfterExceed(dataForm.afterExceed)">
                                        <el-option v-for="item in AFTER_EXCEED" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="预算可上浮金额" prop="floatUpwardAmount" style="width:100%"
                                    label-width="160px">

                                    <el-input-number v-model="dataForm.floatUpwardAmount" :min="0" :max="1000000000"
                                        @blur="getFloatUpwardAmount(dataForm.floatUpwardAmount)" placeholder="请输入"
                                        class="mount-number" :precision="2" :controls="false" style="width:100%;" />
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div class="footer-btn-box">
                    <el-button type="primary" @click="submit()" v-if="pageType != 'look'"
                        :loading="loadingBtn">确定</el-button>
                    <el-button @click="router.go(-1)" :loading="loadingBtn">取 消</el-button>
                </div>
            </page-main>
        </el-form>
        <importForm :dialog-visible="dialogVisible2" :downLoading="downLoading" :showDown="true"
            :acceptOption="acceptOption" @on-submit="exportFiled" @downFile="downFile" @handle-close="handleClose" />
        <FeeTypeDialog :dialogVisible="feeDialogVisible" :selectTypeIds="dataForm.type" @on-update="updateFeeType"
            @handleClose="feeDialogVisible = false" v-if="feeDialogVisible"></FeeTypeDialog>
    </div>
</template>
<script setup>
import { WEEK_LIST, STATUS_LIST, TIME_WEEK_LIST, AFTER_EXCEED, CTROL_METHODS, TEMPLATE_CLASSIFY } from './config'
import { yearFun, singleArr, treeData, unique } from '@/util/index'
import SubjectTree from '@/components/SubjectTree/index.vue';
import FeeTypeDialog from '@/components/FeeTypeDialog/index.vue'
import api from '@/api/index'
import { ElMessage } from 'element-plus';
import { dataListStore } from '@/store/modules/pubiclDataList'
import { xhrFile, downloadFile } from "@/util/downFile";
import { computed } from 'vue';
const route = useRoute()
const router = useRouter()
const dataForm = ref({
    controlBy: 'CYCLE',
    enabled: true,
    templateName: '',
    afterExceed: '',
    date: [],
    startTime: '',
    endTime: '',
    type: '',
    years: '',
    cycleType: '',
    templateType: '',
    floatUpwardAmount: '',
    limitExceed: '0'
})

const formInline = ref({
    subject: '',
    feeType: ''
})

const type = ref('one')

const useSubjectList = ref([])

const weeksList = ref(WEEK_LIST)

const dialogVisible2 = ref(false);

const feeDialogVisible = ref(false)

const acceptOption = ref(".xls,.xlsx");

const importLoading = ref(false);

const downLoading = ref(false);

const formInlineRef = ref(null)

const loading = ref(false)

const loadingBtn = ref(false)

const useFeeTypeVOList = ref([])

const rules = reactive({
    templateName: [
        { required: true, message: '请输入', trigger: 'blur' },
        {
            min: 2, max: 50, required: true,
            message: '字数在2-50之间',
            trigger: 'blur'
        }
    ],
    enabled: [
        { required: true, message: '请选择', trigger: 'blur' },
    ],
    controlBy: [
        { required: true, message: '请选择', trigger: 'blur' },
    ],
    years: [
        { required: true, message: '请选择', trigger: 'blur' },
    ],
    date: [
        { required: true, message: '请选择', trigger: 'blur' },
    ],
    type: [
        { required: false, message: '请选择', trigger: 'blur' },
    ],
    afterExceed: [
        { required: false, message: '请选择', trigger: 'blur' },
    ],
    limitExceed: [
        { required: false, message: '请选择', trigger: 'blur' },
    ],
    cycleType: [
        { required: true, message: '请选择', trigger: 'blur' },
    ],
    floatUpwardAmount: [
        { required: false, message: '请输入', trigger: 'blur' },
    ],
    templateType: [
        { required: true, message: '请输入', trigger: 'blur' },
    ]
})

// 预算控制
const controlOptions = ref([{ label: '是', value: '1' }, { label: '否', value: '0' }])

const formRef = ref(null)

// 科目树删除接口
const interFaceInfo = ref({
    url: 'accoutnDel',//接口名称
    params: {

    },// 参数
    fileName: 'account'
})

// 最高成级写死，叫预算维度
const dataSource = ref([])

const dataStore = dataListStore()

// 年份
const yearOptions = yearFun()

const pageType = ref('add')

const lantId = ref('')

const nodeData = ref(null)

const feeTypeOptions = ref([])

const parentBudgetCategoryList = ref([])

const budgetCategoryVOListOld = ref([])

const isSearch = ref(false)

const treeLen = computed(() => {
    return singleArr(dataSource.value)
})

watch(() => dataForm.value.controlBy, (newVal) => {
    if (newVal == 'CYCLE') weeksList.value = WEEK_LIST
    if (newVal == 'CUSTOM_TIME_RANGE') weeksList.value = TIME_WEEK_LIST
})

onMounted(() => {
    const { type, id } = route.query
    pageType.value = type
    dataStore.setAllfeeTypeVOList([])
    getFeeTypeList()
    if (type != 'add') {
        getDetail(id)
    } else {
        dataStore.submitSubjectId([])
        getSubjectId()
    }

})

const opendFeeTypeDialog = () => {
    if (!nodeData.value) {
        dataForm.value['limitExceed'] = '0'
        return ElMessage.error('请选择科目维度')
    }
    feeDialogVisible.value = true
}

const getSubjectId = () => {
    api.budgetConfig.budgetSubjectId().then(res => {
        console.log(res, 'id')
        lantId.value = res
        let addData = [{
            label: '预算维度',
            parentBudgetCategoryId: '0',
            "afterExceed": "",
            limitExceed: '0',
            "budgetCategoryId": res,
        }]
        dataSource.value = addData
        budgetCategoryVOListOld.value = addData

    })
}

// 获取费用类型列表数据
const getFeeTypeList = () => {
    const params = {
        pageNum: 1,
        pageSize: 10000,
        enabled: true
    }
    api.feeConfig.feeTypeList(params).then(res => {
        feeTypeOptions.value = res.list
    })

}
const findPrent = (curId) => {
    let result = []
    const eacheFind = (id) => {
        let filterReslt = useSubjectList.value.filter(item => item.id == id)
        result = [...result, ...filterReslt]
        if (filterReslt.length > 0 && filterReslt[0].parentBudgetCategoryId != 0) {
            eacheFind(filterReslt[0].parentBudgetCategoryId)
        }
    }
    eacheFind(curId)
    return result
}

const findSubject = (subject) => {
    let result = []
    subject.forEach(item => {
        useSubjectList.value.forEach(itemTwo => {
            if (item == itemTwo.id) {
                result.push(itemTwo)
                if (itemTwo.parentBudgetCategoryId != 0) {
                    result = [...result, ...findPrent(itemTwo.parentBudgetCategoryId)]
                }
            }
        })


    })
    return result
}

const feeTypeSearch = (feeType, list) => {
    let result = []
    feeType.forEach(item => {
        list.forEach(itemTwo => {
            if (itemTwo.feeTypeVOList && itemTwo.feeTypeVOList.length > 0) {
                itemTwo.feeTypeVOList.forEach(itemThree => {
                    if (itemThree.id == item) {
                        result.push(itemTwo)
                        if (itemTwo.parentBudgetCategoryId != 0) {
                            result = [...result, ...findPrent(itemTwo.parentBudgetCategoryId)]
                        }
                    }
                })
            }
        })

    })
    return result
}
const clearDataForm = () => {
    let form = {
        ...dataForm.value
    }
    form.type = []
    form.afterExceed = '',
        form.floatUpwardAmount = undefined
    form.limitExceed = '0'
    dataForm.value = form
}
const searchClick = () => {
    console.log(formInline.value)
    clearDataForm()
    const { subject, feeType } = formInline.value
    let result = [...parentBudgetCategoryList.value]

    if (subject.length > 0 && feeType.length == 0) {
        // 选择了科目
        result = [...result, ...findSubject(subject)]

    } else if (subject.length == 0 && feeType.length > 0) {
        // 选择了费用类型
        result = [...result, ...feeTypeSearch(feeType, useSubjectList.value)]


    } else if (subject.length > 0 && feeType.length > 0) {
        // 选择了科目和费用类型
        let subjectResult = [...parentBudgetCategoryList.value]
        result = [...result, ...feeTypeSearch(feeType, subjectResult)]

    } else {
        // 科目和费用类型都没有选择
        result = budgetCategoryVOListOld.value
    }
    console.log(result, 'resolue')
    result = unique(result, 'id')

    let source = treeData(result, 'budgetCategoryId', 'parentBudgetCategoryId', '0')
    dataSource.value = source
    isSearch.value = true
}

const updateSubject = (list) => {
    useSubjectList.value = [...useSubjectList.value, ...list]
    budgetCategoryVOListOld.value = [...budgetCategoryVOListOld.value, ...list]
}
const deleteSubject = (id) => {
    let findSub = useSubjectList.value.findIndex(item => item.id == id)
    if (findSub > -1) useSubjectList.value.splice(findSub, 1)

    let findSubIndex = budgetCategoryVOListOld.value.findIndex(item => item.id == id)
    if (findSubIndex > -1) budgetCategoryVOListOld.value.splice(findSubIndex, 1)

}
const searchReset = () => {
    formInlineRef.value.resetFields()
    searchClick()
    isSearch.value = false
}


const getDetail = (id) => {
    loading.value = true
    api.budgetConfig.budgetTemplateDetail({ id }).then(res => {
        let allfeeTypeVOList = []
        let subjectList = []
        res.budgetCategoryVOList.forEach(item => {
            item['feeTypeRelationParams'] = item['feeTypeVOList']
            if (item['feeTypeVOList'] && item['feeTypeVOList'].length > 0) {
                let typeList = []
                item['feeTypeVOList'].forEach(itemType => {
                    typeList.push({ orgCode: itemType.orgCode, feeTypeId: itemType.id })
                    allfeeTypeVOList.push(itemType)
                })
                item['feeTypeRelationParams'] = typeList
            }
            item['label'] = item['categoryName']
            //  delete item['feeTypeVOList']
            delete item['categoryName']
            if (item['parentBudgetCategoryId'] == '0') {
                item['label'] = '预算维度'
                parentBudgetCategoryList.value.push(item)
            }

            if (item['feeTypeRelationParams'].length > 0) item['isShowAddBtn'] = true
            item.limitExceed = String(item.limitExceed)
            if (item.parentBudgetCategoryId != '0') subjectList.push(item)
        })

        if (res.years && res.years != '') res.years = res.years.replace('年', '')

        let source = treeData(res.budgetCategoryVOList, 'budgetCategoryId', 'parentBudgetCategoryId', '0')

        if (res.startTime && res.startTime != '') res['date'] = [res.startTime, res.endTime]
        dataStore.submitSubjectId(res.budgetCategoryVOList.filter(subjectItem => subjectItem.parentBudgetCategoryId != '0'))
        dataSource.value = source
        budgetCategoryVOListOld.value = res.budgetCategoryVOList
        dataForm.value = res

        dataStore.setAllfeeTypeVOList(allfeeTypeVOList.map(item => item.id))
        useFeeTypeVOList.value = allfeeTypeVOList

        useSubjectList.value = subjectList
        loading.value = false
    })

}



const handleClose = () => {
    importLoading.value = false
    dialogVisible2.value = false
}

const importHandle = () => {
    importLoading.value = true
    dialogVisible2.value = true

}

// 导入提交
const exportFiled = (val) => {

    if (val && val.file) {
        importLoading.value = true
        let fd = new FormData();
        fd.append("file", val.file);
        api.account.acctOrgExportIn(fd).then((res) => {
            ElMessage({
                type: "success",
                message: "导入成功!",
            });
            importLoading.value = false;
            onSearch();
        }).catch((err => {
            console.log(err)
            importLoading.value = false;
        }))

    }
};
// 下载导入模板
const downFile = () => {
    downLoading.value = true;
    tableLoading.value = true
    api.publicApi.downFile("acctOrganization").then((res) => {
        xhrFile(res.url).then((rex) => {
            downloadFile(rex, "预算模板导入");
            downLoading.value = false;
            tableLoading.value = false
            ElMessage({
                type: "success",
                message: "下载成功!",
            });
        });
    }).catch(err => {
        downLoading.value = false;
        tableLoading.value = false
        importLoading.value = false
    })
};



// 较验 预算科目维度最底层级必须关联类型、超标限制、预算控制
const valieateFeeType = () => {
    const feeTreeFn = (arr) => {
        console.log(arr, 'arrr')
        let text = ''
        arr.forEach(item => {
            if ((!item.children || item.children.length == 0) && (item['afterExceed'] == '' || item['feeTypeRelationParams'].length == 0)) {
                // 是否是最底层
                ElMessage.error(`请完善  末级科目【${item.label}】 的关联费用类型、超标限制、预算控制`)
                throw new Error()

            }
            if (item.children && item.children.length > 0) {
                feeTreeFn(item.children)
            }
        })
    }
    let result = treeData(budgetCategoryVOListOld.value, 'budgetCategoryId', 'parentBudgetCategoryId', '0')
    feeTreeFn(result)
}

const submit = () => {
    if (!formRef) return
    formRef.value.validate(valid => {
        if (valid) {
            console.log(budgetCategoryVOListOld.value, 'budgetCategoryVOListOld.value', dataSource.value)
            let result = treeData(budgetCategoryVOListOld.value, 'budgetCategoryId', 'parentBudgetCategoryId', '0')
            console.log(result, 'resultresult')
            if (!result[0]['children']) return ElMessage.error('请添加科目维度')
            valieateFeeType()

            const { controlBy, enabled, templateName, date, years, cycleType, id, templateType } = dataForm.value
            let data = { enabled, controlBy, templateName, years, cycleType, templateType }
            if (pageType.value == 'edit') data['id'] = id

            if (controlBy == 'CYCLE') {
                //按年份
                data['startTime'] = `${years}-01-01 00:00:00`
                data['endTime'] = `${years}-12-31 23:59:59`
            } else {
                // 定义时间
                data['startTime'] = date[0]
                data['endTime'] = date[1]
            }


            data['budgetTemplateCategoryRelationParamList'] = singleArr(result)
            data['budgetTemplateCategoryRelationParamList'].forEach(item => {
                if (item.addType && item.addType == 'add') item.id = null
            })
            console.log(data, '提交的数据')
            const obj = {
                'add': 'budgetTemplateAdd',
                'copy': 'budgetTemplateAdd',
                'edit': 'budgetTemplateEdit'
            }
            loadingBtn.value = true
            api.budgetConfig[obj[pageType.value]](data).then(res => {
                loadingBtn.value = false
                router.go(-1)
                ElMessage.success('操作成功')
            }).catch(err => {
                loadingBtn.value = false
            })
        } else {
            console.log('error submit!')
            return false
        }
    })
}

const nodeClick = ([data, node, obj]) => {

    let ids = []
    if (!data.floatUpwardAmount) data.floatUpwardAmount = 0
    if (data['feeTypeRelationParams']) {
        data['feeTypeRelationParams'].forEach(item => ids.push(item.feeTypeId))
    }
    if (!data.limitExceed) data.limitExceed = '0'
    dataForm.value['type'] = ids
    dataForm.value['afterExceed'] = data['afterExceed'] || ''
    dataForm.value['limitExceed'] = String(data['limitExceed']) || ''
    dataForm.value['floatUpwardAmount'] = data['floatUpwardAmount'] || ''
    if (data.parentBudgetCategoryId != '0' && !data['children']) nodeData.value = data

}

// 选择费用类型
const updateFeeType = (list) => {

    if (!nodeData.value) {
        dataForm.value['type'] = ''
        return ElMessage.error('请选择科目维度')
    }
    let orgCode = nodeData.value.orgCode
    let arrList = []
    let feeList = []
    list.forEach(item => {
        console.log(item)
        arrList.push({ feeTypeId: item, orgCode })
        feeList.push({ id: item })
    })


    nodeData.value['isShowAddBtn'] = true
    nodeData.value['feeTypeRelationParams'] = arrList
    nodeData.value['feeTypeVOList'] = feeList
    dataForm.value.type = list

    let findIndex = budgetCategoryVOListOld.value.findIndex(item => item.id == nodeData.value.id)
    if (findIndex > -1) {
        budgetCategoryVOListOld.value[findIndex].isShowAddBtn = true
        budgetCategoryVOListOld.value[findIndex].feeTypeRelationParams = arrList
        budgetCategoryVOListOld.value[findIndex].feeTypeVOList = feeList
    }


}
// 选择预算控制
const selectContrl = (val) => {

    if (!nodeData.value) {
        dataForm.value['limitExceed'] = '0'
        return ElMessage.error('请选择科目维度')
    }

    nodeData.value['isShowAddBtn'] = true
    nodeData.value['limitExceed'] = val

    let findIndex = budgetCategoryVOListOld.value.findIndex(item => item.id == nodeData.value.id)
    if (findIndex > -1) {
        budgetCategoryVOListOld.value[findIndex].isShowAddBtn = true
        budgetCategoryVOListOld.value[findIndex].limitExceed = val

    }

}

// 选择超标限制
const selectAfterExceed = (val) => {

    if (!nodeData.value) {
        dataForm.value['afterExceed'] = ''
        return ElMessage.error('请选择科目维度')
    }
    nodeData.value['isShowAddBtn'] = true
    nodeData.value['afterExceed'] = val
    let findIndex = budgetCategoryVOListOld.value.findIndex(item => item.id == nodeData.value.id)
    if (findIndex > -1) {
        budgetCategoryVOListOld.value[findIndex].isShowAddBtn = true
        budgetCategoryVOListOld.value[findIndex].afterExceed = val

    }

}
const getFloatUpwardAmount = (val) => {
    console.log(val)

    if (!nodeData.value) {
        dataForm.value['floatUpwardAmount'] = ''
        return ElMessage.error('请输入可上浮金额')
    }
    nodeData.value['isShowAddBtn'] = true

    let findIndex = budgetCategoryVOListOld.value.findIndex(item => item.id == nodeData.value.id)
    if (findIndex > -1) {
        budgetCategoryVOListOld.value[findIndex].isShowAddBtn = true
        budgetCategoryVOListOld.value[findIndex].floatUpwardAmount = val

    }
}




</script>
<style lang="scss" scoped>
.footer-btn-box {
    text-align: right;
    padding-bottom: 20px;
}
</style>
<style>
.mount-number .el-input-number .el-input__inner {
    text-align: left;
}

.search-box {
    width: 100%;

}

.search-text {
    text-align: center;
    font-size: 14px;
    color: #666;
    margin-top: 55px;
}
</style>
